{% if option.type == type %}

<div class="{{ type }}" id="{{ type }}-{{ key }}">
 <i class="fa fa-spinner fa-spin fa-2x fa-cog"></i> Loading...
</div>

<link rel="stylesheet" type="text/css" href="/static/css/svelte/controls.css">

<script type="text/javascript" src="/static/plugins/{{ plugin }}/controls.js?v={{ sha }}"></script>
<link rel="stylesheet" type="text/css" href="/static/plugins/{{ plugin }}/controls.css">


<script type="text/javascript">

require(['{{ path }}'], function(mod) {

    var App = mod.App,
        data = _.extend({}, mod.data || {}, {{ twig_data | json | raw }});

    var chartData = {{chart.toStruct()|json|raw}};

    // set defaults
    chartData.metadata.visualize = _.extend(
        {{defaults|json|raw}},
        chartData.metadata.visualize
    );

    var chart = new mod.Chart(chartData);
    window.chart2 = chart;
    var getJSON = mod.utils.getJSON;

    var themeCache = {};
    var visCache = {};
    themeCache['{{theme.id}}'] = {{theme.themeData|json|raw}};
    visCache['{{vis.id}}'] = {{vis|json|raw}};

    chart.set({
        writable: true,
        themeData: themeCache['{{theme.id}}'],
        user: {{userArray|json|raw}},
        locales: {{chartLocales|json|raw}},
        themes: {{userThemes|json|raw}},
        visualization: visCache['{{vis.id}}']
    });

    chart.compute('axes', ['visualization'], function(visualization) {
        if (!visualization) {
            return [];
        }
        return _.values(visualization.axes || {});
    });

    function getContext(callback) {
        var win = $('#iframe-vis').get(0).contentWindow;
        var doc = $('#iframe-vis').get(0).contentDocument;
        if (!win || !win.__dw || !win.__dw.vis) {
            return setTimeout(function () {
                getContext(callback);
            }, 200);
        }
        callback(win, doc);
    }

    var app;

    chart.load(dw.backend.__currentData).then(function(ds) {
        chart.set({dataset: ds});

        getContext(function(win, doc) {
            chart.set({vis: win.__dw.vis});

            document.querySelector('#{{ type }}-{{ key }}').innerHTML = '';

            app = mod.app = new App({
                store: chart,
                target: document.querySelector('#{{ type }}-{{ key }}'),
                data: data
            });
        });
    });

    var lastHash = null;

    var editHistory = [];
    var dontPush = false;
    var historyPos = 0;
    var passiveMode = false;

    chart.on('state', function (_ref) {
        var changed = _ref.changed;
        var current = _ref.current;
        var previous = _ref.previous;

        // observe theme changes and load new theme data if needed
        if (changed.theme) {
            // console.log('theme has changed', current.theme);
            if (themeCache[current.theme]) {
                // re-use cached theme
                chart.set({themeData: themeCache[current.theme]});
            } else {
                // load new theme data
                getJSON(('/api/themes/' + (current.theme)), function (res) {
                    if (res.status == 'ok') {
                        themeCache[current.theme] = res.data.data;
                        chart.set({themeData: res.data.data});
                    } else {
                        console.warn('theme not loaded', res);
                    }
                });
            }
        }

        if (changed.type) {
            if (app && app.destroy) {
                app.destroy();
            }
            if (visCache[current.type]) {
                // re-use cached visualization
                chart.set({visualization: visCache[current.type]});
            } else {
                // load new vis data
                getJSON(('/api/visualizations/' + (current.type)), function (res) {
                    if (res.status == 'ok') {
                        visCache[current.type] = res.data.data;
                        chart.set({visualization: visCache[current.type]});
                    } else {
                        console.warn('vis not loaded', res);
                    }
                });
            }
        }

        if (previous && changed.title || changed.theme || changed.type ||
            changed.metadata || changed.language || changed.lastEditStep) {
            chart.store(function() {
                var iframe = document.querySelector('#iframe-vis');
                if (iframe && iframe.contentWindow) {
                    var win = iframe.contentWindow;
                    if (win.__dw && win.__dw.saved) {
                        win.__dw.saved();
                    }
                }
            });
            if (!dontPush) {
                var s = JSON.stringify(chart.serialize());
                if (historyPos > 0) {
                    // throw away edit history until the current pos
                    editHistory.splice(0, historyPos);
                }
                if (editHistory[0] != s) editHistory.unshift(s);
                editHistory.length = Math.min(editHistory.length, 50);
                historyPos = 0;
            }
            if (!passiveMode && dw && dw.backend && dw.backend.currentChart) {
                var iframe = document.querySelector('#iframe-vis');
                if (iframe && iframe.contentWindow) {
                    var win = iframe.contentWindow;
                    if (win.__dw && win.__dw.attributes) {
                        win.__dw.attributes(current);
                    }
                }

                dw.backend.currentChart.set('metadata', JSON.parse(JSON.stringify(current.metadata)));
            }
        }
    });

    window.addEventListener('keypress', function(evt) {
        if (evt.key == 'z' && evt.ctrlKey) {
            var old_pos = historyPos;
            historyPos += evt.altKey ? -1 : 1;
            if (editHistory[historyPos]) {
                dontPush = true;
                chart.set(JSON.parse(editHistory[historyPos]));
                dontPush = false;
            } else {
                historyPos = old_pos;
            }
        }
    });


    // observe changes to old chart object
    dw.backend.currentChart.onChange(function(ds, changed) {
        passiveMode = true;
        var attr = dw.backend.currentChart.attributes();
        chart.set(attr);
        // if (changed == 'metadata.data.changes') {
        //     const dataset = chart.dataset(true);
        //     chart.set({ dataset });
        // }
        setTimeout(function() {
            passiveMode = false;
        }, 100)
    });
})
</script>

{% endif %}
